<template>
  <el-drawer
    title="生成订单XML"
    :visible.sync="visible"
    direction="rtl"
    size="60%"
    :before-close="handleClose"
    :wrapper-closable="false"
    custom-class="order-xml-drawer"
  >
    <div class="drawer-container">
      <div class="drawer-content">
        <el-form :model="form" label-width="120px" size="small" :rules="rules" ref="form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="GUID" prop="guid">
                <el-input v-model="form.guid" disabled>
                  <el-button slot="append" @click="generateGuid">重新生成</el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订单编号" prop="orderNo">
                <el-input v-model="form.orderNo" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申报类型" prop="appType">
                <el-select v-model="form.appType" placeholder="请选择申报类型">
                  <el-option label="新增" value="1" />
                  <el-option label="变更" value="2" />
                  <el-option label="删除" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报时间" prop="appTime">
                <el-input v-model="form.appTime" disabled>
                  <el-button slot="append" @click="refreshAppTime">刷新</el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单类型" prop="orderType">
                <el-select v-model="form.orderType" placeholder="请选择订单类型">
                  <el-option label="进口" value="I" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电商平台代码" prop="ebpCode">
                <el-input v-model="form.ebpCode" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电商平台名称" prop="ebpName">
                <el-input v-model="form.ebpName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电商企业代码" prop="ebcCode">
                <el-input v-model="form.ebcCode" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="电商企业名称" prop="ebcName">
                <el-input v-model="form.ebcName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电商企业名称" prop="ebcName">
                <el-input v-model="form.ebcName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品价值" prop="goodsValue">
                <el-input v-model="form.goodsValue" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运费" prop="freight">
                <el-input v-model="form.freight"  />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="优惠金额" prop="discount">
                <el-input v-model="form.discount"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税款" prop="taxTotal">
                <el-input v-model="form.taxTotal"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实付金额" prop="acturalPaid">
                <el-input v-model="form.acturalPaid" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="币制" prop="currency">
                <el-input v-model="form.currency" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订购人注册号" prop="buyerRegNo">
                <el-input v-model="form.buyerRegNo" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订购人姓名" prop="buyerName">
                <el-input v-model="form.buyerName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="订购人电话" prop="buyerTelephone">
                <el-input v-model="form.buyerTelephone" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="证件号码" prop="buyerIdNumber">
                <el-input v-model="form.buyerIdNumber" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付企业代码" prop="payCode">
                <el-input v-model="form.payCode" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="支付企业名称" prop="payName">
                <el-input v-model="form.payName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付交易编号" prop="payTransactionId">
                <el-input v-model="form.payTransactionId" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货人" prop="consignee">
                <el-input v-model="form.consignee" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="收货人电话" prop="consigneeTelephone">
                <el-input v-model="form.consigneeTelephone" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收货地址" prop="consigneeAddress">
                <el-input v-model="form.consigneeAddress" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="note">
                <el-input v-model="form.note" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">商品信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="商品序号" prop="gnum">
                <el-input v-model="form.gnum" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="企业商品名称" prop="itemName">
                <el-input v-model="form.itemName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品规格型号" prop="gmodel">
                <el-input v-model="form.gmodel" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="单位" prop="unit">
                <el-input v-model="form.unit" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="qty">
                <el-input v-model="form.qty"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单价" prop="price">
                <el-input v-model="form.price" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="总价" prop="totalPrice">
                <el-input v-model="form.totalPrice"  />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="原产国" prop="country">
                <el-input v-model="form.country" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">基础报文传输信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="传输企业代码" prop="copCode">
                <el-input v-model="form.copCode" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="传输企业名称" prop="copName">
                <el-input v-model="form.copName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="报文传输模式" prop="dxpMode">
                <el-input v-model="form.dxpMode" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="报文传输编号" prop="dxpId">
                <el-input v-model="form.dxpId" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="drawer-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="generateXml">生成XML</el-button>
      </div>
    </div>

    <!-- XML内容弹窗 -->
    <el-dialog
      title="生成的XML"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleDialogClose"
      append-to-body
    >
      <el-input
        type="textarea"
        v-model="xmlContent"
        :rows="20"
        readonly
      />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyXml">复制XML</el-button>
        <el-button type="success" @click="downloadXml">下载XML</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </el-drawer>
</template>

<script>
export default {
  name: 'OrderXmlDrawer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: [String, Number],
      default: ''
    },
    detailForm: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        guid: '',
        orderNo: '',
        appType: '1',
        appStatus: '2',
        appTime: '',
        orderType: 'I',
        ebpCode: '',
        ebpName: '',
        ebcCode: '3210660A0E',
        ebcName: '扬州数贸港跨境电子商务有限公司',
        goodsValue: '0.0',
        freight: '0.0',
        discount: '0.0',
        taxTotal: '0.0',
        acturalPaid: '0.0',
        currency: '142',
        buyerRegNo: '',
        buyerName: '',
        buyerTelephone: '',
        buyerIdType: '1',
        buyerIdNumber: '',
        payCode: '',
        payName: '',
        payTransactionId: '',
        consignee: '',
        consigneeTelephone: '',
        consigneeAddress: '',
        note: '',
        // 商品表体参数
        gnum: '1',
        itemName: '',
        gmodel: '',
        unit: '',
        qty: '1',
        price: '0.0',
        totalPrice: '0.0',
        country: '',
        // 基础报文传输信息
        copCode: '3210660A0E',
        copName: '扬州数贸港跨境电子商务有限公司',
        dxpMode: 'DXP',
        dxpId: 'DXPENT2024716238'
      },
      rules: {
        guid: [
          { required: true, message: 'GUID不能为空', trigger: 'blur' }
        ],
        orderNo: [
          { required: true, message: '订单编号不能为空', trigger: 'blur' }
        ],
        appType: [
          { required: true, message: '请选择申报类型', trigger: 'change' }
        ],
        ebpCode: [
          { required: true, message: '电商平台代码不能为空', trigger: 'blur' }
        ],
        ebpName: [
          { required: true, message: '电商平台名称不能为空', trigger: 'blur' }
        ],
        ebcCode: [
          { required: true, message: '电商企业代码不能为空', trigger: 'blur' }
        ],
        ebcName: [
          { required: true, message: '电商企业名称不能为空', trigger: 'blur' }
        ],
        goodsValue: [
          { required: true, message: '商品价值不能为空', trigger: 'blur' },
          { type: 'number', message: '商品价值必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        freight: [
          { required: true, message: '运费不能为空', trigger: 'blur' },
          { type: 'number', message: '运费必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        discount: [
          { required: true, message: '优惠金额不能为空', trigger: 'blur' },
          { type: 'number', message: '优惠金额必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        taxTotal: [
          { required: true, message: '税款不能为空', trigger: 'blur' },
          { type: 'number', message: '税款必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        acturalPaid: [
          { required: true, message: '实付金额不能为空', trigger: 'blur' },
          { type: 'number', message: '实付金额必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        currency: [
          { required: true, message: '币制不能为空', trigger: 'blur' }
        ],
        buyerName: [
          { required: true, message: '订购人姓名不能为空', trigger: 'blur' }
        ],
        buyerTelephone: [
          { required: true, message: '订购人电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        buyerIdNumber: [
          { required: true, message: '证件号码不能为空', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号码', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '收货人不能为空', trigger: 'blur' }
        ],
        consigneeTelephone: [
          { required: true, message: '收货人电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        consigneeAddress: [
          { required: true, message: '收货地址不能为空', trigger: 'blur' }
        ],
        // 商品表体验证规则
        itemName: [
          { required: true, message: '企业商品名称不能为空', trigger: 'blur' }
        ],
        gmodel: [
          { required: true, message: '商品规格型号不能为空', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '单位不能为空', trigger: 'blur' }
        ],
        qty: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
          { type: 'number', message: '数量必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        price: [
          { required: true, message: '单价不能为空', trigger: 'blur' },
          { type: 'number', message: '单价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        totalPrice: [
          { required: true, message: '总价不能为空', trigger: 'blur' },
          { type: 'number', message: '总价必须为数字', trigger: 'blur', transform: value => Number(value) }
        ],
        country: [
          { required: true, message: '原产国不能为空', trigger: 'blur' }
        ]
      },
      xmlContent: '',
      dialogVisible: false
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.form.orderNo = this.orderId
        this.generateGuid()
        this.refreshAppTime()

        // 填充基本信息
        if (this.detailForm) {
          //支付平台信息
          this.form.payCode = this.detailForm.paycomCode || ''
          this.form.payName = this.detailForm.paycomName || ''
          // 金额相关
          this.form.goodsValue = this.detailForm.amount || '0.0'
          this.form.discount = this.detailForm.discount || '0.0'
          this.form.freight = this.detailForm.distributionfee || '0.0'
          this.form.taxTotal = this.detailForm.tax || '0.0'
          this.form.acturalPaid = this.detailForm.realPayment || '0.0'
          // 电商平台信息
          this.form.ebpCode = this.detailForm.ebpCode || ''
          this.form.ebpName = this.detailForm.ebpName || ''
          // 订购人信息
          this.form.buyerRegNo = this.detailForm.contactMobile || ''
          this.form.buyerName = this.detailForm.buyerName || ''
          this.form.buyerTelephone = this.detailForm.contactMobile || ''
          this.form.buyerIdType = '1'
          this.form.buyerIdNumber = this.detailForm.ConsigneeCode1 || ''
          // 收货人信息
          this.form.consignee = this.detailForm.contactName || ''
          this.form.consigneeTelephone = this.detailForm.contactMobile || ''
          // 收货地址拼接
          this.form.consigneeAddress = [
            this.detailForm.contactAddr || '',
            this.detailForm.detailAddr || ''
          ].filter(Boolean).join('')
          // 支付信息
          this.form.payTransactionId = this.detailForm.payOrderNo || ''

          // 商品表体信息 - 只设置价格
          if (this.detailForm.order_goods && this.detailForm.order_goods[0]) {
            const goods = this.detailForm.order_goods[0]
            // 保留两位小数
            this.form.price = Number(goods.goods_price || 0).toFixed(2)
            this.form.qty = goods.goods_num || '1'
            this.form.totalPrice = Number(goods.goods_amount || 0).toFixed(2)
            this.form.gmodel = goods.hg_gmodel || ''
            this.form.unit = goods.hg_unit || ''
            this.form.country = goods.hg_originCountry || ''
            this.form.itemName = goods.goods_name || ''
          }
        }
      } else {
        // 关闭时重置表单
        this.$refs.form && this.$refs.form.resetFields()
      }
    }
  },
  methods: {
    refreshAppTime() {
      const now = new Date()
      this.form.appTime = 
        now.getFullYear() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0') +
        String(now.getHours()).padStart(2, '0') +
        String(now.getMinutes()).padStart(2, '0') +
        String(now.getSeconds()).padStart(2, '0')
    },
    generateGuid() {
      const hexDigits = '0123456789abcdef'
      const segments = [8, 4, 4, 4, 12] // GUID格式：8-4-4-4-12
      const guid = segments.map(len => {
        let segment = ''
        for (let i = 0; i < len; i++) {
          segment += hexDigits.charAt(Math.floor(Math.random() * 16))
        }
        return segment
      }).join('-')
      this.form.guid = guid.toUpperCase()
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$refs.form.resetFields()
    },
    handleDialogClose(done) {
      done()
    },
    generateXml() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 处理价格，确保XML中的价格保留两位小数
          const price = Number(this.form.price).toFixed(2)
          const totalPrice = Number(this.form.totalPrice).toFixed(2)

          this.refreshAppTime()
          this.xmlContent = `<?xml version="1.0" encoding="UTF-8"?>
<ceb:CEB311Message xmlns:ceb="http://www.chinaport.gov.cn/ceb" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" guid="${this.form.guid}" version="1.0">
  <ceb:Order>
    <ceb:OrderHead>
      <ceb:guid>${this.form.guid}</ceb:guid>
      <ceb:appType>${this.form.appType}</ceb:appType>
      <ceb:appTime>${this.form.appTime}</ceb:appTime>
      <ceb:appStatus>${this.form.appStatus}</ceb:appStatus>
      <ceb:orderType>${this.form.orderType}</ceb:orderType>
      <ceb:orderNo>${this.form.orderNo}</ceb:orderNo>
      <ceb:ebpCode>${this.form.ebpCode}</ceb:ebpCode>
      <ceb:ebpName>${this.form.ebpName}</ceb:ebpName>
      <ceb:ebcCode>${this.form.ebcCode}</ceb:ebcCode>
      <ceb:ebcName>${this.form.ebcName}</ceb:ebcName>
      <ceb:goodsValue>${this.form.goodsValue}</ceb:goodsValue>
      <ceb:freight>${this.form.freight}</ceb:freight>
      <ceb:discount>${this.form.discount}</ceb:discount>
      <ceb:taxTotal>${this.form.taxTotal}</ceb:taxTotal>
      <ceb:acturalPaid>${this.form.acturalPaid}</ceb:acturalPaid>
      <ceb:currency>${this.form.currency}</ceb:currency>
      <ceb:buyerRegNo>${this.form.buyerTelephone}</ceb:buyerRegNo>
      <ceb:buyerName>${this.form.buyerName}</ceb:buyerName>
      <ceb:buyerTelephone>${this.form.buyerTelephone}</ceb:buyerTelephone>
      <ceb:buyerIdType>${this.form.buyerIdType}</ceb:buyerIdType>
      <ceb:buyerIdNumber>${this.form.buyerIdNumber}</ceb:buyerIdNumber>
      <ceb:payCode>${this.form.payCode}</ceb:payCode>
      <ceb:payName>${this.form.payName}</ceb:payName>
      <ceb:payTransactionId>${this.form.payTransactionId}</ceb:payTransactionId>
      <ceb:batchNumbers></ceb:batchNumbers>
      <ceb:consignee>${this.form.consignee}</ceb:consignee>
      <ceb:consigneeTelephone>${this.form.consigneeTelephone}</ceb:consigneeTelephone>
      <ceb:consigneeAddress>${this.form.consigneeAddress}</ceb:consigneeAddress>
      <ceb:note>${this.form.note}</ceb:note>
    </ceb:OrderHead>
    <ceb:OrderList>
      <ceb:gnum>${this.form.gnum}</ceb:gnum>
      <ceb:itemNo></ceb:itemNo>
      <ceb:itemName>${this.form.itemName}</ceb:itemName>
      <ceb:gmodel>${this.form.gmodel}</ceb:gmodel>
      <ceb:itemDescribe></ceb:itemDescribe>
      <ceb:barCode></ceb:barCode>
      <ceb:unit>${this.form.unit}</ceb:unit>
      <ceb:qty>${this.form.qty}</ceb:qty>
      <ceb:price>${price}</ceb:price>
      <ceb:totalPrice>${totalPrice}</ceb:totalPrice>
      <ceb:currency>${this.form.currency}</ceb:currency>
      <ceb:country>${this.form.country}</ceb:country>
      <ceb:note></ceb:note>
    </ceb:OrderList>
  </ceb:Order>
  <ceb:BaseTransfer>
    <ceb:copCode>${this.form.ebcCode}</ceb:copCode>
    <ceb:copName>${this.form.ebcName}</ceb:copName>
    <ceb:dxpMode>DXP</ceb:dxpMode>
    <ceb:dxpId>${this.form.dxpId}</ceb:dxpId>
    <ceb:note></ceb:note>
  </ceb:BaseTransfer>
</ceb:CEB311Message>`
          this.dialogVisible = true // 显示弹窗
        } else {
          this.$message.error('请填写完整所有必填项')
          return false
        }
      })
    },
    copyXml() {
      navigator.clipboard.writeText(this.xmlContent).then(() => {
        this.$message.success('XML已复制到剪贴板')
        this.dialogVisible = false // 复制成功后关闭弹窗
      }).catch(() => {
        this.$message.error('复制失败，请手动复制')
      })
    },
    downloadXml() {
      const blob = new Blob([this.xmlContent], { type: 'text/xml' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      // 使用订单号作为文件名
      link.download = `order_${this.form.orderNo}.xml`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(link.href)
      this.$message.success('XML文件已下载')
    }
  }
}
</script>

<style scoped>
.order-xml-drawer {
  overflow: hidden;
}
.drawer-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.drawer-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
.drawer-footer {
  padding: 20px;
  background: #fff;
  text-align: right;
  border-top: 1px solid #e8e8e8;
}
.xml-content {
  margin: 20px 0;
}
.copy-btn {
  margin-top: 10px;
}
.el-divider {
  margin: 24px 0;
}
</style> 